    //
//  MyAccountView.m
//  iFlower
//
//  Created by Hoang Thuc on 15/07/2010.
//  Copyright 2010 iNIL. All rights reserved.
//

#import "MyAccountView.h"
#import "Address.h"
#import "iFlowerAppDelegate.h"
#import "Request.h"
#import "Country.h"
#import "State.h"
#import "Utility.h"
#import "MyAccountDetailView.h"

@interface MyAccountView()

@property (nonatomic, retain) NSMutableArray* addresses; 
@property (nonatomic, retain) NSMutableArray *arrayState;
@property (nonatomic, retain) NSMutableArray *arrayCountry;


@end


@implementation MyAccountView

-(IBAction)buttonClickCountry:(id)sender
{
	self.P2 = TRUE;
	self.actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	[self.actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
	CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
	self.pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
	self.pickerView.showsSelectionIndicator = YES;
	self.pickerView.dataSource = self;
	self.pickerView.delegate = self;
	[self.actionSheet addSubview:self.pickerView];
	//---
	UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];
	closeButton.momentary = YES; 
	closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
	closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
	closeButton.tintColor = [UIColor blackColor];
	[closeButton addTarget:self action:@selector(dismissActionSheet1:) forControlEvents:UIControlEventValueChanged];
	[self.actionSheet addSubview:closeButton];
	[closeButton release];
	
	[self.actionSheet showInView:self.view];
	
	[self.actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}


-(void)dismissActionSheet1:(id)sender
{
	self.P2 = FALSE;
	[self.actionSheet dismissWithClickedButtonIndex:0 animated:YES];
	self.labelCountry.text = [[self.arrayCountry objectAtIndex:[self.pickerView selectedRowInComponent:0]]countryName];	
	self.CountryCode = [[self.arrayCountry objectAtIndex:[self.pickerView selectedRowInComponent:0]]countryCode];	
}


-(IBAction)buttonClickState:(id)sender
{
	//if([self.txtCity.text length] != 0)
		self.P1 = TRUE;
	
	self.actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	[self.actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
	CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
	self.pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
	self.pickerView.showsSelectionIndicator = YES;
	self.pickerView.dataSource = self;
	self.pickerView.delegate = self;
	[self.actionSheet addSubview:self.pickerView];
	//---
	UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];
	closeButton.momentary = YES; 
	closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
	closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
	closeButton.tintColor = [UIColor blackColor];
	[closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
	[self.actionSheet addSubview:closeButton];
	[closeButton release];
	
	[self.actionSheet showInView:self.view];
	
	[self.actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}


-(void)dismissActionSheet:(id)sender
{
	self.P1 = FALSE;
	[self.actionSheet dismissWithClickedButtonIndex:0 animated:YES];
	self.labelState.text =[ [self.arrayState objectAtIndex:[self.pickerView selectedRowInComponent:0]] state];
	self.StateCode = [ [self.arrayState objectAtIndex:[self.pickerView selectedRowInComponent:0]] stateCode];
}


- (void) contentLoaded:(NSNotification*) notification
{
	NSLog(@"content loaded");
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[self.addresses removeAllObjects];
	for (NSDictionary* dictionary in [[[Request sharedRequest] entries] objectAtIndex:0])
	{
		Address* entry = [[Address new] autorelease];
		if (entry != nil)
		{
			entry.label = [dictionary objectForKey: @"label"];
			entry.firstName = [dictionary objectForKey: @"firstname"];
			entry.lastName = [dictionary objectForKey: @"lastname"];
			entry.addressLine1 = [dictionary objectForKey: @"address"];
			entry.addressLine2 = [dictionary objectForKey: @"address2"];
			entry.city = [dictionary objectForKey: @"city"];
			entry.state = [dictionary objectForKey: @"state"];
			entry.zipCode = [dictionary objectForKey: @"zipcode"];
			entry.country = [dictionary objectForKey: @"country"];
			entry.phone = [dictionary objectForKey: @"phone"];
			entry.fax = [dictionary objectForKey: @"fax"];
			entry.addressId = [dictionary objectForKey: @"id"];
			[self.addresses addObject: entry];
		}
	}
	if([[[Request sharedRequest] entries]count]>1)
	{
		for (NSDictionary* dictionary in [[[Request sharedRequest] entries] objectAtIndex:1])
		{
			Country* entry = [[Country new] autorelease];
			if (entry != nil)
			{
				entry.countryCode = [dictionary objectForKey: @"country_code"] ;
				entry.countryName = [dictionary objectForKey: @"country"];
				entry.displayStates = [[dictionary objectForKey:@"display_states"] boolValue];
				entry.region = [dictionary objectForKey:@"region"];
				[self.arrayCountry addObject: entry];
			}
		}
		for (NSDictionary* dictionary in [[[Request sharedRequest] entries] objectAtIndex:2])
		{
			State* entry = [[State new] autorelease];
			if (entry != nil)
			{
				entry.state = [dictionary objectForKey: @"state"];
				entry.stateId = [dictionary objectForKey: @"stateid"];
				entry.stateCode = [dictionary objectForKey: @"state_code"];
				entry.countryCode = [dictionary objectForKey: @"country_code"];
				//[self.arrayStatePicker addObject:[dictionary objectForKey: @"state"]];
				[self.arrayState addObject: entry];
			}
		}		
	}
	[self.tableView reloadData];
	self.tableView.hidden = NO;
	self.addView.hidden = YES;
	[[iFlowerAppDelegate shareDelegate] hideLoadingView];
	
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	return YES;
}
- (void) contentFailed:(NSNotification*) notification
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	NSLog(@"content failed");
	[[iFlowerAppDelegate shareDelegate] hideLoadingView];
}
-(IBAction)addPressed:(id)sender
{
	if([self.txtLabel.text length] == 0)
	{
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"Enter label name!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release];
	}
	else if ([self.txtFirstname.text length] == 0){
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"Enter first name!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release];
	}
	else if ([self.txtLastName.text length] == 0){
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"Enter last name!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release];
	}
	else if ([self.txtAddress.text length] == 0) {
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"Enter address name!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release];
	}
	else if ([self.txtPhone.text length] == 0) {
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"Enter the phone!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release];
	}
	else if ([self.txtCity.text length] == 0) {
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"Enter city name!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release];
	}
	else if ([self.txtPostCode.text length] == 0) {
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"Enter the post code!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release];
	}
	else {
		[[iFlowerAppDelegate shareDelegate] showLoadingView];
		
		[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentLoaded:) name: @"ContentLoaded" object: nil];
		[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentFailed:) name: @"ContentFailed" object: nil];
		
		Address* address = [[Address new] autorelease];
		address.label = self.txtLabel.text;
		address.fax = @"";
		address.phone=self.txtPhone.text;
		address.firstName = self.txtFirstname.text;
		address.lastName = self.txtLastName.text;
		address.addressLine1 = self.txtAddress.text;
		address.addressLine2 = @"";
		address.city = self.txtCity.text;
		address.state = self.StateCode;
		address.country = self.CountryCode;
		address.zipCode = self.txtPostCode.text;
		
		
		[[Request sharedRequest] addAddress:address user:[[iFlowerAppDelegate shareDelegate] user]];
	}
}
-(IBAction)buttonMenu:(id)sender
{
	[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)buttonSearch:(id)sender
{
    [[iFlowerAppDelegate shareDelegate] showLoadingView];
	
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentLoaded:) name: @"ContentLoaded" object: nil];
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentFailed:) name: @"ContentFailed" object: nil];
	
	[[Request sharedRequest] getAddressBooks:[[iFlowerAppDelegate shareDelegate] user]];
}

-(void)autoLoad
{
	[[iFlowerAppDelegate shareDelegate] showLoadingView];
	
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentLoaded:) name: @"ContentLoaded" object: nil];
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentFailed:) name: @"ContentFailed" object: nil];
	
	[[Request sharedRequest] getAddressBooks:[[iFlowerAppDelegate shareDelegate] user]];
}

-(IBAction)buttonAdd:(id)sender
{
	self.addView.hidden = NO;
}

-(IBAction)button_Next:(id)sender
{
	[Utility showAlert:@"Order history will be available in next version!"];
	/*MyAccountView2 * account2 = [[MyAccountView2 alloc]initWithNibName:@"MyAccountView2" bundle:nil];
	[self.navigationController pushViewController:account2 animated:YES];
	[account2 release];*/
}
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [super viewDidLoad];
	//self.arrayStatePicker = [[NSMutableArray alloc]init];
	//self.arrayCountryPicker = [[NSMutableArray alloc]init];
	
	[self autoLoad];
	
	self.tableView.hidden = YES;
	self.addresses = [[NSMutableArray alloc] initWithCapacity:5];
	self.arrayState = [[NSMutableArray alloc] initWithCapacity:5];
	self.arrayCountry = [[NSMutableArray alloc] initWithCapacity:5];
	CGRect r = self.addView.frame;
	r.origin.x = 50;
	r.origin.y = 117;
	self.addView.frame = r;
	[self.view addSubview:self.addView];
	self.addView.hidden = YES;
	//self.arrayStatePicker = [[NSMutableArray alloc]init];
	//[self.arrayStatePicker addObject:@"ha noi"];
	//[self.arrayStatePicker addObject:@"hai phong"];
	
	//self.arrayCountryPicker = [[NSMutableArray alloc]init];
	//[self.arrayCountryPicker addObject:@"viet nam"];
	//[self.arrayCountryPicker addObject:@"lao"];
	
	self.P1 = FALSE;
	self.P2 = FALSE;

}

/*
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
	[self.txtPhone resignFirstResponder];
	[self.txtCity resignFirstResponder];
	[self.txtState resignFirstResponder];
	[self.txtCountry resignFirstResponder];
	[self.txtPostCode resignFirstResponder];
	
	[super touchesBegan:touches withEvent:event];
}
*/

-(IBAction)TextFiedDone:(id)sender
{
	[self.txtLabel resignFirstResponder];
	[self.txtFirstname resignFirstResponder];
	[self.txtLastName resignFirstResponder];
	[self.txtAddress resignFirstResponder];
	[self.txtPhone resignFirstResponder];
	[self.txtCity resignFirstResponder];
	//[self.txtState resignFirstResponder];
	//[self.txtCountry resignFirstResponder];
	[self.txtPostCode resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
	[UIView beginAnimations:nil context:NULL];
	self.view.frame = CGRectMake(self.view.frame.origin.x, 
								 self.view.frame.origin.y - 120, 
								 self.view.frame.size.width,
								 self.view.frame.size.height);
	[UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
	[UIView beginAnimations:nil context:NULL];
	self.view.frame = CGRectMake(self.view.frame.origin.x, 
								 self.view.frame.origin.y + 120, 
								 self.view.frame.size.width,
								 self.view.frame.size.height);
	[UIView commitAnimations];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[self.addView release];
	[self.addresses release];
	[self.pickerView release];
	[self.actionSheet release];
	//[self.arrayStatePicker release];
	//[self.arrayCountryPicker release];
	[self.labelState release];
	[self.labelCountry release];
    [super dealloc];
}
#pragma mark -UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	return [self.addresses count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"Cell";
	
	UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
	}
	Address* a = (Address*)[self.addresses objectAtIndex:indexPath.row];
	cell.textLabel.text = a.label;
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	return cell;
}	
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	MyAccountDetailView * detail = [[MyAccountDetailView alloc]initWithNibName:@"MyAccountDetailView" bundle:nil];
	detail.address = (Address*)[self.addresses objectAtIndex:indexPath.row];
	[self.navigationController pushViewController:detail animated:YES];
	[detail release];
	
}

#pragma mark -
#pragma mark Picker View Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
	
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
	if(self.P1==TRUE)
	//{
		return [self.arrayState count];
	//}
	//else if (self.P2 == TRUE) {
	else 
		
	

		return [self.arrayCountry count];
	//}
	//else 


	//return;

}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
	if(self.P1==TRUE)
	//{
		return [[self.arrayState objectAtIndex:row] state];
	//}
	//else if(self.P2 == TRUE){
	else 
	

		 return [[self.arrayCountry objectAtIndex:row] countryName];
	//}
	//else


	
	//return ;
}

@end
